import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;



public class Seguranca {
	public static PrivateKey getPrivateKey(File cert, String alias, String senha) throws Exception {
		KeyStore ks = KeyStore.getInstance("JKS");
		char[] pwd = senha.toCharArray();
		InputStream is = new FileInputStream(cert);
		ks.load(is, pwd);
		is.close();
		Key key = ks.getKey(alias, pwd);
		if(key instanceof PrivateKey) {
			return (PrivateKey) key;
		}
		return null;
	}


	public static PublicKey getPublicKey(File cert, String alias, String senha) throws Exception {
		KeyStore ks = KeyStore.getInstance("JKS");
		char[] pwd = senha.toCharArray();
		InputStream is = new FileInputStream(cert);
		ks.load(is, pwd);
		Key key = ks.getKey(alias, pwd);
		Certificate c =  ks.getCertificate(alias);
		PublicKey p = c.getPublicKey();
		return p;
	}

	
	public static byte[] criarAssinatura(PrivateKey key, byte[] buffer) throws Exception {
		Signature sig = Signature.getInstance("MD5");
		sig.initSign(key);
		sig.update(buffer, 0, buffer.length);
		return sig.sign();
	}

	
	public static boolean checarAssinatura(PublicKey key, byte[] buffer, byte[] signed) throws Exception {
		Signature sig = Signature.getInstance("MD5");
		sig.initVerify(key);
		sig.update(buffer, 0, buffer.length);
		return sig.verify(signed);
	}

}
